package com.softserveinc.fragments.map;

import java.util.List;

import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

public abstract class BalloonItemizedOverlay extends
		ItemizedOverlay<OverlayItem> {

	private static final String TAG = BalloonItemizedOverlay.class
			.getSimpleName();

	private final MapController mc;
	private final MapView mapView;

	private final MapPopup mapPopup;

	private boolean popupAdded = false;

	private OverlayItem currentFocussedItem;
	private int currentFocussedIndex;

	public BalloonItemizedOverlay(final Drawable defaultMarker,
			final MapPopup mapPopup, final MapView mapView) {
		super(defaultMarker);

		this.mapView = mapView;
		this.mapPopup = mapPopup;

		mc = mapView.getController();
	}

	protected abstract boolean onBalloonTap(final int index,
			final OverlayItem OverlayItem);

	@Override
	protected final boolean onTap(final int index) {

		currentFocussedIndex = index;
		currentFocussedItem = createItem(index);

		createAndDisplayBalloonOverlay();

		mc.animateTo(currentFocussedItem.getPoint());

		return true;
	}

	private void hideBalloon() {
		mapPopup.hide();
	}

	private void hideOtherBalloons(final List<Overlay> overlays) {
		for (Overlay overlay : overlays) {

			if (overlay instanceof BalloonItemizedOverlay) {
				((BalloonItemizedOverlay) overlay).hideBalloon();
			}
		}

	}

	private void createAndDisplayBalloonOverlay() {
		List<Overlay> mapOverlays = mapView.getOverlays();
		hideOtherBalloons(mapOverlays);

		if (currentFocussedItem != null) {
			mapPopup.setData(currentFocussedItem);
		}

		GeoPoint point = currentFocussedItem.getPoint();
		MapView.LayoutParams params = new MapView.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, point,
				MapView.LayoutParams.BOTTOM_CENTER);
		params.mode = MapView.LayoutParams.MODE_MAP;

		if (!popupAdded) {
			mapPopup.setPopupOnClickListener(new OnClickListener() {

				@Override
				public void onClick(final View v) {
					Log.i(TAG, "tapped on balloon");

					onBalloonTap(currentFocussedIndex, currentFocussedItem);
				}
			});
		}

		mapPopup.showAt(params);

		popupAdded = true;
	}
}